#include "talk/examples/crossfirewall/xmltask/xmlsendertask.h"
#include "talk/xmpp/constants.h"

#ifdef POSIX
#include <arpa/inet.h>
#endif

#define GOOGLE_CLIENT_NODE "http://www.google.com/xmpp/client/caps"

using namespace buzz;
namespace str
{
	CXMLSenderTask::CXMLSenderTask(XmppTaskParentInterface* parent,const std::string &cn/*=""*/, int type /*=PACKAGE_TYPE_PRESENT*/ ) :
		buzz::XmppTask(parent),done_(false),m_strComputerName(cn), m_iType(type)
	{
	}

	CXMLSenderTask::~CXMLSenderTask(void)
	{
	}

	int CXMLSenderTask::ProcessStart()
	{
		if (SendStanza(stanza_.get()) != buzz::XMPP_RETURN_OK) {
			return STATE_ERROR;
		}
		else {
			done_ = true;
			return STATE_DONE;
		}
	}

	int CXMLSenderTask::ProcessResponse()
	{
		if (done_) return STATE_DONE;
		else return STATE_BLOCKED;
	}

	buzz::XmlElement * CXMLSenderTask::GenerateXml()
	{
		buzz::XmlElement *ret = NULL;
		switch (m_iType)
		{
		case PACKAGE_TYPE_PRESENT:
			ret = this->GeneratePresentXml();
			break;
		case PACKAGE_TYPE_PING:
			ret = this->GeneratePingXml();
			break;
		default:
			break;
		}
		return ret;
	}

	buzz::XmlElement * CXMLSenderTask::GeneratePresentXml()
	{
		buzz::XmlElement * result = NULL;
		result = new buzz::XmlElement(QN_PRESENCE);
		std::string caps;
		result->AddElement(new buzz::XmlElement(QN_CAPS_C, true));
		result->AddAttr(QN_NODE, GOOGLE_CLIENT_NODE, 1);
		result->AddAttr(QN_VER, m_strComputerName, 1);
		result->AddAttr(QN_EXT, "share-v1", 1);
		return result;
	}

	buzz::XmlElement * CXMLSenderTask::GeneratePingXml()
	{
		buzz::XmlElement *result = MakeIq(STR_GET, JID_EMPTY, task_id());
		result->AddElement( new buzz::XmlElement(QN_PING) );
		return result;
	}

	buzz::XmppReturnStatus CXMLSenderTask::SendToXmppServer(  )
	{
		if (GetState() != STATE_INIT)
			return buzz::XMPP_RETURN_BADSTATE;
		buzz::XmlElement * query = GenerateXml();
		
		stanza_.reset( query );
		return buzz::XMPP_RETURN_OK;
	}

	buzz::XmppReturnStatus CXMLSenderTask::SendToJID( const std::string & toJid )
	{
		if (GetState() != STATE_INIT)
			return buzz::XMPP_RETURN_BADSTATE;
		buzz::XmlElement * query = GenerateXml();
		query->AddAttr(QN_TO, toJid);
		stanza_.reset( query );
		return buzz::XMPP_RETURN_OK;
	}
}
